package com.ftg.learn.chapter10.jdbc;


import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

/**
 * @author kangjx
 * @createTime 2022/7/20
 */
public class LearnReflect {

    public void q1() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        String path = "com.ftg.learn.chapter10.jdbc.Student";

        //类 class对象
        Class c = Class.forName(path);
        Object obj = c.newInstance();


        Student s = (Student) obj;

        s.setSsex("男");
        System.out.println(s.getSsex());

        //能过一个类的地址完成这个类的实例化

    }

    public void q2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
//        通过类名直接获取
        Class c = Student.class;
        Object obj = c.newInstance();
        //取到里面所有属性
        Field sname = c.getField("sname");
        System.out.println(sname.getName());
        Type t = sname.getGenericType();
        System.out.println(t.getTypeName());
        sname.set(obj,"张三");
        System.out.println(sname.get(obj));
//        getFields 获得是公共字段
//        Field[] fs = c.getDeclaredFields();
//        for (int i = 0; i < fs.length; i++) {
//            System.out.println(fs[i].getName());
//        }
    }

    public void q3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Student s = new Student();
        Class c2 = s.getClass();
        Method m1 = c2.getMethod("setSname", String.class);
        m1.invoke(s,"张三李四");


        Method m = c2.getMethod("getSname");
        Object obj = m.invoke(s);
        System.out.println(obj);
        System.out.println(m.getName());

        c2.getMethods();
    }

    public void q4() throws NoSuchFieldException, IntrospectionException, InvocationTargetException, IllegalAccessException {
        Student s = new Student();
        Class c2 = s.getClass();

        Field fs = c2.getDeclaredField("sname");

        PropertyDescriptor pd = new PropertyDescriptor(fs.getName(),c2);

        Method fsSett = pd.getWriteMethod();
        fsSett.invoke(s,"张三");

        System.out.println(pd.getReadMethod().invoke(s));
    }

    public static void main(String[] args) throws NoSuchFieldException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IntrospectionException {
        LearnReflect lr = new LearnReflect();
        lr.q4();
    }

//    Class
//    Field
//    Method
//    PropertyDescriptor
}
